package heap;

import java.util.PriorityQueue;

public class leetcode378有序矩阵中第K小的元素 {
    // 优先队列
    public int kthSmallest(int[][] matrix, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2 - o1);
        int row = matrix.length;
        int col = matrix[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (k > 0) {
                    queue.offer(matrix[i][j]);
                    k--;
                } else {
                    if (matrix[i][j] < queue.peek()) {
                        queue.poll();
                        queue.offer(matrix[i][j]);
                    }
                }
            }
        }
        return queue.peek();
    }
}
